//
//  YJStatus.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/17.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit

class YJStatus: NSObject {
    
    /// 微博创建时间
    var created_at: String?
    
    /// 微博ID
    var id: Int64 = 0
    
    /// 微博信息内容
    var text: String?
    
    var source: String? {
        didSet {
            // 当KVC设置来源:<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>
            // 截取>(.*?)<: 微博 weibo.com
            // 在didSet给source不会再次调用didSet
            source = source?.sinaSource()
        }
    }
    
    /// 微博配图,服务器返回的是数组,数组里面又是字典,后续操作不方便,需要解析字典,当KVC的时候,模型来提供图片URL地址数组
    var pic_urls: [[String : AnyObject]]? {
        didSet {
            if pic_urls?.count == 0 {
                return
            }
            
            storePictureURLs = [URL]()
            for dict in pic_urls! {
                // if let 可选绑定会导致代码嵌套过多,提供守卫
                guard let urlString = dict["thumbnail_pic"] as? String else {
                    JPrint("没有值")
                    continue
                }
                guard let url = URL(string: urlString) else {
                    JPrint("url 没有值")
                    continue
                }
                storePictureURLs?.append(url)
            }
        }
        
    }
    
    /// 微博配图,里面存储的是 微博配图的url地址
    var storePictureURLs: [URL]?
    
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 表态数
    var attitudes_count: Int = 0
    
    var user: YJUser?
    
    /// 被转发的微博
    var retweeted_status: YJStatus?
    
    /// 行高
    var rowHeight: CGFloat?
    
    /// 字典转模型 重载构造函数
    init(dict: [String : Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String : Any] {
                user = YJUser(dict: dict)
            }
            return
        }
        if key == "retweeted_status" {
            if let dict = value as? [String : Any] {
                retweeted_status = YJStatus(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {

    }
    
    // 对象打印
    override var description: String {
        // 只读计算型属性
        let keys = ["created_at", "id", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count", "user"]
        
        return "\n\t微博模型: \(dictionaryWithValues(forKeys: keys).description)"
    }

}
